#!/usr/bin/env python

import sys
import time
import signal
import thread
import socket
from daemon import Daemon
from requesthandler import RequestHandler
#from socket import *

class ScreenDaemon(Daemon):

	def __init__ (self,pidfile):
		Daemon.__init__(self,pidfile)
		
	def run(self):
		#create server socket
		#create an INET, STREAMing socket
    		serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		serversocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
    		serversocket.bind(("localhost", 5555))
    		serversocket.listen(5) #5 simultaneous requests
		while True:
			#accept connections from outside
			(connection, address) = serversocket.accept()
			rh = RequestHandler(connection)
			rh.start()
					
if __name__ == "__main__":
	daemon = ScreenDaemon('/tmp/screendaemon.pid')
	if len(sys.argv) == 2:
		if 'start' == sys.argv[1]:
			daemon.start()
		elif 'stop' == sys.argv[1]:
			daemon.stop()
		elif 'restart' == sys.argv[1]:
			daemon.restart()
		else:
			print "Unknown command"
			sys.exit(2)
		sys.exit(0)
	else:
		print "usage: %s start|stop|restart" % sys.argv[0]
		sys.exit(2)
